<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in">
      <div class="hearder-search">
        <el-col :span="24" class="breadcrumb-container input-val-box mb-10">
          <el-input v-model="searchname" placeholder="物料名称" size="small" class="w-200 mr-10"></el-input>
          <el-select clearable v-model="stock_id" placeholder="选择物料仓库" class="mr-10">
            <el-option v-for="item in stockList" :key="item.id" :label="item.name" :value="item.id">{{item.name}}</el-option>
          </el-select>
          <el-button type="primary" size="small" @click="searchFn"><i class="el-icon-search"></i>搜索</el-button>
          <el-button size="small" @click="refreshFn"><i class="el-icon-refresh"></i>重置刷新</el-button>
        </el-col>
        <el-col :span="24" class="breadcrumb-container">
          <div class="applyBox">
            <span class="titlebook">请勾选申请物料名称：</span><span class="applycart" @click="showApplyCart"><i
                  class="iconfont icontushu"></i><span>共{{applyBookBoxNumber.length}}样,点击查看</span></span>
          </div>
        </el-col>
      </div>
      <!--本体列表，数据 -->
      <div class="table-body">
        <div class="table-body-box">
          <!--@row-click="rowClick"-->
          <el-table
                  ref="table"
                  :data="arryList"
                  :stripe="tableStripe"
                  :border="tableBorder"
                  tooltip-effect="dark"
                  style="width: 100%"
                  header-cell-class-name="table-text-c"
                  cell-class-name="table-text-c"
                  @selection-change="handleSelectionChange"
                  @select-all="selectAll"
                  @select="selectFnBox"
                  @row-click="rowClick">
            <!--<el-table-column width="50">-->
            <!--<template slot-scope="scope">-->
            <!--<el-radio v-model="radio" :label="scope.row.id" class="radioCheckBox">{{scope.row.id}}</el-radio>-->
            <!--</template>-->
            <!--</el-table-column>-->
            <el-table-column
                    type="selection"
                    width="50">
            </el-table-column>
            <el-table-column
                    prop="name"
                    label="物料名称">
            </el-table-column>
            <el-table-column
                    label="可领库存"
                    width="110">
              <template slot-scope="scope">
                {{scope.row.number}} / {{scope.row.unit}}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!--工具条 分页-->
      <el-col :span="24" class="toolbar">
        <el-pagination
                background
                layout="total, prev, pager, next"
                :total="page.total"
                :page-size="page.pagesize"
                @current-change="handleSizeChange">
        </el-pagination>
      </el-col>
    </div>
    <applyMateriel :visible.sync="cartVisible" :eidtOption="applyBookBox" @detelBook="detelBook"
                   @submitApplyBook="submitApply" @changeApply="changeApply" ref="applyBox"></applyMateriel>
  </div>
</template>

<script>
  import {pagination} from '@/utils/util.js'
  import api from '@/utils/api.js'
  import applyMateriel from '@/components/dialog/applyMateriel.vue'
  import {materielChoose} from '@/api/admin/materiel'

  export default {
    components: {
      applyMateriel
    },
    data () {
      return {
        stockList:[],//仓库数组
        stock_id:null,//仓库id
        cartVisible: false,
        searchname: '',
        tableStripe: true, // 是否斑马栏
        tableBorder: true, // 单元格右边边框
        handleSelection: null, // checked选中框
        applyBookBox: {}, // 选中图书信息
        applyBookBoxInit: {}, // 本页面对应对象
        radio: null,
        num: 1,
        content: '',
        applyBox: null,
        arryList: [],
        page: {
          pageindex: pagination.pageIndex,
          pagesize: pagination.pageSize,
          total: pagination.total
        },
        applyBookBoxNumber: []
      }
    },
    created () {
      this.InitFn()
      this.InitStockFn()
    },
    methods: {
      // 获取仓库数组
    InitStockFn() {
      this.$fetch(this.api.mater.warehouse.index, {
        p: this.page.pageindex
      }).then((response) => {
        if (response.code === 0) {
          this.stockList = response.list.data
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
      // 初始化
      InitFn () {
        let _this = this
        materielChoose({p: this.page.pageindex, name: this.searchname,warehouse_id:this.stock_id}).then(response=>{
          console.log('可申请的物料：', response)
          if (response.code === 0) {
            let applyBookBoxInit = {}
            let table_ = []
            for (let i in response.list.data) {
              // if (response.list.data[i].number) {
              response.list.data[i].num = 1
              response.list.data[i].content = ''
              applyBookBoxInit[response.list.data[i].id] = response.list.data[i]
              table_.push(response.list.data[i])
              // }
            }
            this.applyBookBoxInit = applyBookBoxInit
            this.arryList = table_
            this.page.total = response.list.total
            _this.$nextTick(function () {
              _this.checked() // 每次更新了数据，触发这个函数即可。
            })
          } else {
          }
        })
        // this.$fetch(api.admin_materiel_index, {p: this.page.pageindex, name: this.searchname}).then((response) => {
        //   if (response.code === 0) {
        //     let applyBookBoxInit = {}
        //     let table_ = []
        //     for (let i in response.list.data) {
        //       // if (response.list.data[i].number) {
        //         response.list.data[i].num = 1
        //         response.list.data[i].content = ''
        //         applyBookBoxInit[response.list.data[i].id] = response.list.data[i]
        //         table_.push(response.list.data[i])
        //       // }
        //     }
        //     this.applyBookBoxInit = applyBookBoxInit
        //     this.arryList = table_
        //     this.page.total = response.list.total
        //     _this.$nextTick(function () {
        //       _this.checked() // 每次更新了数据，触发这个函数即可。
        //     })
        //   } else {
        //   }
        // }).catch((err) => {
        //   console.log(err)
        // })
      },
      searchFn () {
        this.arryList = []
        this.page.pageindex = 1
        this.InitFn()
      },
      refreshFn () {
        this.arryList = []
        this.page.pageindex = 1
        this.searchname = ''
        this.stock_id = null
        this.InitFn()
      },
      // 分页
      handleSizeChange (val) {
        this.page.pageindex = val
        this.arryList = []
        this.InitFn()
      },
      // // 行选中
      // rowClick(option) {
      //   this.applyBookBox = option.name
      //   this.radio = option.id
      //   this.applyBox = option
      // },
      // 提交新增，编辑书籍
      submitApply () {
        // 判断新增 编辑
        if (JSON.stringify(this.applyBookBox) !== '{}') {
          let _self = this
          let paramData = []
          for (let i in this.applyBookBox) {
            let data = {}
            data.number = this.applyBookBox[i].num
            data.materiel_id = this.applyBookBox[i].id
            data.content = this.applyBookBox[i].content
            paramData.push(data)
          }
          this.$post(api.admin_materiel_log_apply, {list: JSON.stringify(paramData)}).then((response) => {
            if (response.code === 0) {
              this.radio = null
              this.num = 1
              this.applyBookBox = {} // 更新视图对象
              this.applyBookBoxNumber = []
              this.$refs.applyBox.closeFn()
              this.InitFn()
              this.$message.success('申请成功！')
            } else {
              this.$message.error(response.msg)
            }
          }).catch((err) => {
            console.log(err)
          })
        } else {
          this.$message.error('请选择申请的图书')
        }
      },
      // 设置默认选中
      checked () {
        console.log('默认选项判断', this.applyBookBox)
        for (let i = 0; i < this.arryList.length; i++) {
          if (this.applyBookBox[this.arryList[i].id]) {
            console.log('数值', i)
            this.$refs.table.toggleRowSelection(this.arryList[i], true)
          } else {
            this.$refs.table.toggleRowSelection(this.arryList[i], false)
          }
        };
      },
      // 重置验证
      resetForm () {
        console.log('取消')
        this.editFormVisible = false
        this.$refs['editForm'].resetFields()
      },
      handleClose (done) {
        done()
        this.$refs['editForm'].resetFields()
      },
      showApplyCart () {
        if (this.applyBookBoxNumber.length) {
          this.cartVisible = true
        } else {
          this.$message.error('请选择申请物料')
        }
      },
      // 选项发生变化
      handleSelectionChange (val) {
        this.handleSelection = val
      },
      // 点击全选
      selectAll (val) {
        // 全选所有跟空值，即使页面已经选择2项
        console.log('点击全选', val)
        console.log(val) // 所有选中值
        let applyBookBox = this.applyBookBox
        if (val.length !== 0) {
          // this.handleSelection = val
          for (let i = 0; i < val.length; i++) {
            if (!applyBookBox[val[i].id]) {
              // 不存在图书
              applyBookBox[val[i].id] = val[i]
            }
          }
        } else {
          // 清除所有 arryList
          for (let i = 0; i < this.arryList.length; i++) {
            if (this.applyBookBox[this.arryList[i].id]) {
              // 存在图书删除
              delete applyBookBox[this.arryList[i].id]
            }
          }
        }
        this.applyBookBox = Object.assign({}, this.applyBookBox, applyBookBox) // 更新视图对象
        this.applyBookBoxNumber = Object.keys(this.applyBookBox)
      },
      // 点击单选
      selectFnBox (val) {
        // 选择的是当前所有的选中，还需要比对未选中项 applyBookBoxInit
        console.log('本页面的列表数据', this.applyBookBoxInit)
        console.log('点击单选', val)
        let applyBookBox = this.applyBookBox
        if (val.length) {
          // 有选项 对本页面的选项进行比对
          let valBox = {}
          for (let i = 0; i < val.length; i++) {
            valBox[val[i].id] = val[i]
          }
          for (let i in this.applyBookBoxInit) {
            if (valBox[i]) {
              // 存在图书删除
              applyBookBox[i] = this.applyBookBoxInit[i]
            } else {
              delete applyBookBox[i]
            }
          }
        } else {
          // 清除所有 arryList
          for (let i in this.applyBookBoxInit) {
            delete applyBookBox[i]
          }
        }
        this.applyBookBox = Object.assign(this.applyBookBox, applyBookBox) // 更新视图对象
        this.applyBookBoxNumber = Object.keys(this.applyBookBox)
        console.log('单选过后applyBookBox:', this.applyBookBox)
      },
      // 单行选中
      rowClick (row, column, event) {
        console.log('行：', row, this.applyBookBox)
        if(!row.number){
          this.$message.error('库存不足')
          return
        }
        let applyBookBox_ = this.applyBookBox
        if (!applyBookBox_[row.id]) {
          applyBookBox_[row.id] = row
        } else {
          delete applyBookBox_[row.id]
        }
        this.applyBookBox = Object.assign({}, this.applyBookBox, applyBookBox_) // 更新视图对象
        console.log('this.applyBookBox:', this.applyBookBox)
        this.applyBookBoxNumber = Object.keys(this.applyBookBox)
        let that = this
        this.$nextTick(function () {
          that.checked() // 每次更新了数据，触发这个函数即可。
        })
      },
      detelBook (optionid) {
        let applyBookBox = this.applyBookBox
        console.log('shan删除的对象：', applyBookBox)
        delete applyBookBox[optionid]
        this.applyBookBox = Object.assign({}, this.applyBookBox, applyBookBox) // 更新视图对象
        this.applyBookBoxNumber = Object.keys(this.applyBookBox)
        this.InitFn()
      },
      // 编辑选择申请的数量内容
      changeApply (option) {
        this.applyBookBox = option
      }
    },
    mounted () {
    }
  }
</script>

<style lang="scss">
  .radioCheckBox .el-radio__label {
    display: none;
  }

  .applyBoxs {
    border: 1px solid #eee;
    border-radius: 3px;
    width: 100%;
    padding: 10px;
    overflow: hidden;
    display: flex;
    align-items: center;
    .el-input {
      width: 100px;
      margin-right: 10px;
    }
    .box-spans {
      border: 1px solid #409EFF;
      color: #fff;
      background: #409EFF;
      display: inline-block;
      border-radius: 3px;
      padding: 0 10px;
      cursor: pointer;
      position: relative;
      margin: 0 10px;
      height: 40px;
      line-height: 40px;
    }
  }

  #tablebox {
    display: flex;
    flex-direction: column;
  }

  .el-table {
    color: #000;
  }

  .right-box .container .main .content-container .input-val-box .input-top {
    width: 250px;
  }

</style>
